import axios from 'axios'
import {ERR_OK} from "@/config/api-config/config";
import {getUid} from "@/common/js/uid";

const debug = process.env.NODE_ENV !== 'production'

export async function getLyric(mid) {
    const url = debug ? '/api/lyric' : 'http://ustbhuangyi.com/music/api/lyric'
    const data = {
        g_tk: 1928093487,
        inCharset: 'utf-8',
        outCharset: 'utf-8',
        notice: 0,
        songmid: mid,
        platform: 'yqq',
        hostUin: 0,
        needNewCode: 0,
        categoryId: 10000000,
        pcachetime: +new Date(),
        format: 'json'
    }
    let result = await axios.get(url,{
        params: data
    })
    return result.data
}

export async function getSongUrl(songs) {
    const url = debug ? '/api/getPurlUrl' : 'http://ustbhuangyi.com/music/api/getPurlUrl'
    let mids = []
    let types = []

    songs.forEach(song => {
        mids.push(song.mid)
        types.push(0)
    })

    const urlMid = getUrlMid(mids,types)
    const data = {
        inCharset: 'utf-8',
        outCharset: 'utf-8',
        notice: 0,
        g_tk: 5381,
        format: 'json',
        platform: 'h5',
        needNewCode: 1,
        uin: 0
    }

    let result = (await axios.post(url, {
        comm: data,
        req_0: urlMid
    })).data
    if(result.code === ERR_OK){
        let urlMid = result.req_0
        if(urlMid && urlMid.code === ERR_OK){
            const purlMap = {}
            urlMid.data.midurlinfo.forEach(item => {
                if(item.purl)
                    purlMap[item.songmid] = item.purl

            })
            if(Object.keys(purlMap).length > 0)
                return purlMap
            else
                return new Error('purlMap is undefined')
        }

    }
}

function getUrlMid(mids,types) {
    const guid = getUid()
    return {
        module: 'vkey.GetVkeyServer',
        method: 'CgiGetVkey',
        param: {
            guid,
            songmid: mids,
            songtype: types,
            uin: '0',
            loginflag: 0,
            platform: '23'
        }
    }
}
